package com.elite.groovy.kh;

import cn.com.dh.AESUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @author chenyouwei
 * @date 2018/10/25 15:45
 */
public class PostRequestThirdParty {
    private static Map<String, String> map = new HashMap<>();
    static {
        map.put("10001", "asda23asdqweq123");
        map.put("10002", "fo12jd89qdsgh123");
        map.put("10003", "910ecqm12y18q123");
    }
    private static Logger logger = LoggerFactory.getLogger(PostRequestThirdParty.class);
    private static String appId = "10001";
    private static String assertKey = "asda23asdqweq123";
    private static String fromType = "001";
    private static String projectId = "100121";

    public static String getReqData(String reqData) {
        // reqData加密
        try {
            reqData = AESUtil.encrypt(reqData, assertKey);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return reqData;
    }

    public static String getSign(String fromType, String appId, String projectId, String timestamp, String reqData) {
        TreeMap<String, String> param = new TreeMap<>();
        param.put("appId", appId);
        param.put("projectId", projectId);
        param.put("timestamp", timestamp);
        param.put("fromType", fromType);
        param.put("reqData", reqData);
        // 生成签名
        StringBuilder stringBuilder = new StringBuilder();
        for (String key : param.keySet()) {
            stringBuilder.append(key).append("=").append(param.get(key));
        }
        stringBuilder.append(assertKey);
        logger.info("待加密数据:{}", stringBuilder);
        return getSign1(stringBuilder.toString());
    }

    public static String getSign1(String content) {
        return DigestUtils.sha256Hex(content);
    }

    public String assertRequest(String reqData, String url) {
        String timestamp = String.valueOf(System.currentTimeMillis());
        Map<String, String> param = new TreeMap<>();
        param.put("appId", appId);
        param.put("fromType", fromType);
        param.put("projectId", projectId);
        param.put("timestamp", timestamp);
        param.put("reqData", reqData);
        // 生成签名
        StringBuilder stringBuilder = new StringBuilder();
        for (String key : param.keySet()) {
            stringBuilder.append(key).append("=").append(param.get(key));
        }
        stringBuilder.append(assertKey);
//            System.out.println(stringBuilder.toString());
        param.put("sign", getSign1(stringBuilder.toString()));

        String jsonStr = JSON.toJSONString(param);
        System.out.println("【TEST】 ------json param =" + jsonStr);
        String result = sendPost(url, param);
        System.out.println("【TEST】 结果是:" + result);

        JSONObject jsonObj = JSONObject.parseObject(result);
        String encrypt = jsonObj.getString("data");
        String decrypt = null;
        if (StringUtils.isBlank(encrypt)) {
            return decrypt;
        }
        try {
            decrypt = AESUtil.decrypt(new String(encrypt.getBytes(), StandardCharsets.UTF_8), assertKey);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("-----------" + decrypt);
        return decrypt;
    }


    public String sendPost(String url, Map<String, String> map) {
        // 设置参数
        List<NameValuePair> formParams = new ArrayList<>();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        // 编码
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(formParams, Consts.UTF_8);
        // 取得HttpPost对象
        HttpPost httpPost = new HttpPost(url);
        // 参数放入Entity
        httpPost.setEntity(formEntity);
        CloseableHttpResponse response = null;
        String result = null;
        try {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            // 执行post请求
            response = httpclient.execute(httpPost);
            // 得到entity
            HttpEntity entity = response.getEntity();
            // 得到字符串
            result = EntityUtils.toString(entity);
        } catch (IOException e) {
            logger.error(e.getMessage());
        } catch (Exception e) {
            logger.error(e.getMessage());
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    logger.error(e.getMessage());
                }
            }
        }
        return result;
    }
}
